<template>
  <div class="flex flex-col">
    <el-card shadow="never" style="margin-bottom: 1rem;">
      <template #header>
        <!-- 标题 -->
        <div class="flex flex-row items-center justify-between">
          <CardTitle title="订单统计" />
          <!-- 查询条件 -->
          <ShortcutDateRangePicker ref="shortcutDateRangePicker" @change="getTradeTrendData">
            <el-button class="ml-4" @click="handleExport" :loading="exportLoading"
              v-hasPermi="['statistics:trade:export']">
              <Icon icon="ep:download" class="mr-1" />导出
            </el-button>
          </ShortcutDateRangePicker>
        </div>
      </template>
      <!-- 统计值 -->
      <el-row :gutter="16">
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单数量" tooltip="订单数量" icon="fa-solid:shopping-cart" icon-color="bg-purple-100"
            icon-bg-color="text-purple-500" :decimals="0" :value="orderList.orderCount || 0" />
        </el-col>
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单关闭数量" tooltip="订单关闭数量" icon="fa-solid:times-circle" icon-color="bg-blue-100"
            icon-bg-color="text-blue-500" :decimals="0" :value="orderList.closedOrderCount || 0" />
        </el-col>
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单售后数量" tooltip="订单售后数量" icon="ep:warning-filled" icon-color="bg-green-100"
            icon-bg-color="text-green-500" :decimals="0" :value="orderList.afterSalesOrderCount || 0" />
        </el-col>
      </el-row>
      <!-- 统计图表 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :md="16" :sm="24">
          <el-skeleton :loading="trendLoading" animated>
            <Echart :height="350" :options="orderNumberChartOptions" />
          </el-skeleton>
        </el-col>
        <el-col :md="8" :sm="24">
          <el-skeleton :loading="trendLoading" animated>
            <Echart :height="350" :options="orderTypeChartOptions" />
          </el-skeleton>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never" style="margin-bottom: 1rem;">
      <template #header>
        <!-- 标题 -->
        <div class="flex flex-row items-center justify-between">
          <CardTitle title="金额统计" />
          <!-- 查询条件 -->
        </div>
      </template>
      <!-- 统计值 -->
      <el-row :gutter="16">
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单金额" tooltip="订单金额" icon="fa-solid:yen-sign" icon-color="bg-blue-100"
            icon-bg-color="text-blue-500" prefix="￥" :decimals="0" :value="amountList.orderQuote || 0" />
        </el-col>
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单支付金额" tooltip="订单支付金额" icon="fa-solid:money-check-alt" icon-color="bg-yellow-100"
            icon-bg-color="text-yellow-500" prefix="￥" :decimals="0" :value="amountList.orderRepayment || 0" />
        </el-col>
      </el-row>
      <!-- 统计图表 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :md="24" :sm="24">
          <el-skeleton :loading="trendLoading" animated>
            <Echart :height="500" :options="orderPriceChartOptions" />
          </el-skeleton>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never" style="margin-bottom: 1rem;">
      <template #header>
        <!-- 标题 -->
        <div class="flex flex-row items-center justify-between">
          <CardTitle title="交付统计" />
        </div>
      </template>
      <!-- 统计值 -->
      <el-row :gutter="16">
        <el-col :md="6" :sm="12" :xs="24">
          <SummaryCard title="订单交付数量" tooltip="订单交付数量" icon="fa-solid:award" icon-color="bg-yellow-100"
            icon-bg-color="text-yellow-500" :decimals="0" :value="deliverList.orderDeliverCount || 0" />
        </el-col>
      </el-row>
      <!-- 统计图表 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :md="16" :sm="24">
          <el-skeleton :loading="trendLoading" animated>
            <Echart :height="350" :options="deliverNumberChartOptions" />
          </el-skeleton>
        </el-col>
        <el-col :md="8" :sm="24">
          <el-skeleton :loading="trendLoading" animated>
            <Echart :height="350" :options="deliverTimeChartOptions" />
          </el-skeleton>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import * as TradeStatisticsApi from '@/api/mall/statistics/trade'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { EChartsOption } from 'echarts'
import { DataComparisonRespVO } from '@/api/mall/statistics/common'
import { TradeSummaryRespVO, TradeTrendSummaryRespVO } from '@/api/mall/statistics/trade'
import { calculateRelativeRate, fenToYuan } from '@/utils'
import download from '@/utils/download'
import { CardTitle } from '@/components/Card'
import * as DateUtil from '@/utils/formatTime'
import dayjs from 'dayjs'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** 交易统计 */
defineOptions({ name: 'TradeStatistics' })

const message = useMessage() // 消息弹窗

const trendLoading = ref(true) // 交易状态加载中
const exportLoading = ref(false) // 导出的加载中
const summary = ref<DataComparisonRespVO<TradeSummaryRespVO>>() // 交易统计数据
const trendSummary = ref<DataComparisonRespVO<TradeTrendSummaryRespVO>>() // 交易状况统计数据
const shortcutDateRangePicker = ref()
const orderList = ref({
  orderCount: 0,
  closedOrderCount: 0,
  afterSalesOrderCount: 0
})
const amountList = ref({
  orderQuote: 0,
  orderRepayment: 0
})
const deliverList = ref({
  orderDeliverCount: 0
})

/** 处理查询时间 */
const getTradeTrendData = async () => {
  trendLoading.value = true
  // 1. 处理时间: 开始与截止在同一天的, 折线图出不来, 需要延长一天
  const times = shortcutDateRangePicker.value.times
  if (DateUtil.isSameDay(times[0], times[1])) {
    // 前天
    times[0] = DateUtil.formatDate(dayjs(times[0]).subtract(1, 'd'))
  }
  // 查询数据
  await Promise.all([getOrderList(), getOrderStatusList(), getAmountList(), getTestDeliverList()])
  trendLoading.value = false
}

/** 获取订单数量数据 */
const getOrderList = async () => {
  // 查询数据
  const times = shortcutDateRangePicker.value.times
  const list = await TradeStatisticsApi.getOrder({ times })
  orderList.value = list
  // 处理数据
  for (let item of list.mallStatisticsTrendObjs) {
    item.orderCountTrend = item.orderCountTrend
    item.closedOrderCountTrend = item.closedOrderCountTrend
    item.afterSalesOrderCountTrend = item.afterSalesOrderCountTrend
  }
  // 更新 Echarts 数据
  if (orderNumberChartOptions.dataset && orderNumberChartOptions.dataset['source']) {
    orderNumberChartOptions.dataset['source'] = list.mallStatisticsTrendObjs
  }
}

/** 获取订单状态数据 */
const getOrderStatusList = async () => {
  const times = shortcutDateRangePicker.value.times
  const list = await TradeStatisticsApi.getOrderStatusCount({ times })
  const dictDataList = getIntDictOptions(DICT_TYPE.ORDER_STATUS)
  orderTypeChartOptions.series![0].data = dictDataList.map((dictData) => {
    const orderCount = list.find(
      (item) => item.status === dictData.value
    )?.orderCount
    return {
      name: dictData.label,
      value: orderCount || 0
    }
  })
}

/** 获取订单金额数据 */
const getAmountList = async () => {
  // 查询数据
  const times = shortcutDateRangePicker.value.times
  const list = await TradeStatisticsApi.getAmount({ times })
  amountList.value = list
  // 处理数据
  for (let item of list.orderAmountTrendObjs) {
    item.orderQuote = item.orderQuote
    item.orderRepayment = item.orderRepayment
  }
  // 更新 Echarts 数据
  if (orderPriceChartOptions.dataset && orderPriceChartOptions.dataset['source']) {
    orderPriceChartOptions.dataset['source'] = list.orderAmountTrendObjs
  }
}

/** 获取订单交付数据 */
const getTestDeliverList = async () => {
  // 查询数据
  const times = shortcutDateRangePicker.value.times
  const list = await TradeStatisticsApi.getTestDeliver({ times })
  deliverList.value = list
  // 处理数据
  for (let item of list.orderDeliverTrendObjs) {
    item.orderDeliverCount = item.orderDeliverCount
  }
  // 更新 Echarts 数据
  if (deliverNumberChartOptions.dataset && deliverNumberChartOptions.dataset['source']) {
    deliverNumberChartOptions.dataset['source'] = list.orderDeliverTrendObjs
  }

  for (let order of list.orderDeliverPeriodObjs) {
    order.name = order.value + '周内'
    order.value = order.count
  }
  deliverTimeChartOptions.series![0].data = list.orderDeliverPeriodObjs
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const times = shortcutDateRangePicker.value.times
    const data = await TradeStatisticsApi.exportTradeStatisticsExcel({ times })
    download.excel(data, '交易状况.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 订单数量配置 */
const orderNumberChartOptions = reactive<EChartsOption>({
  dataset: {
    dimensions: ['date', 'orderCountTrend', 'closedOrderCountTrend', 'afterSalesOrderCountTrend'],
    source: []
  },
  grid: {
    left: 20,
    right: 40,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  legend: {
    top: 50
  },
  series: [
    { name: '订单数量', type: 'line' },
    { name: '订单关闭数量', type: 'line' },
    { name: '订单售后数量', type: 'line' },
  ],
  toolbox: {
    feature: {
      // 数据区域缩放
      dataZoom: {
        yAxisIndex: false // Y轴不缩放
      },
      brush: {
        type: ['lineX', 'clear'] // 区域缩放按钮、还原按钮
      },
      saveAsImage: { show: true, name: '交易状况' } // 保存为图片
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    padding: [5, 10]
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisTick: {
      show: false
    }
  },
  yAxis: {
    axisTick: {
      show: false
    }
  }
}) as EChartsOption

/** 订单类型配置 */
const orderTypeChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'item',
    confine: true,
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'right'
  },
  // roseType: 'area',
  series: [
    {
      name: '订单类型',
      type: 'pie',
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
}) as EChartsOption

/** 订单金额配置 */
const orderPriceChartOptions = reactive<EChartsOption>({
  dataset: {
    dimensions: ['date', 'orderQuote', 'orderPayment'],
    source: []
  },
  grid: {
    left: 20,
    right: 40,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  legend: {
    top: 50
  },
  series: [
    {
      name: '订单金额', type: 'line', smooth: true,
      areaStyle: {},
    },
    {
      name: '订单支付金额', type: 'line', smooth: true,
      areaStyle: {},
    },
  ],
  toolbox: {
    feature: {
      // 数据区域缩放
      dataZoom: {
        yAxisIndex: false // Y轴不缩放
      },
      brush: {
        type: ['lineX', 'clear'] // 区域缩放按钮、还原按钮
      },
      saveAsImage: { show: true, name: '交易状况' } // 保存为图片
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    padding: [5, 10]
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisTick: {
      show: false
    }
  },
  yAxis: {
    axisTick: {
      show: false
    }
  }
}) as EChartsOption

/** 交付数量配置 */
const deliverNumberChartOptions = reactive<EChartsOption>({
  dataset: {
    dimensions: ['date', 'orderDeliverCount'],
    source: []
  },
  grid: {
    left: 20,
    right: 40,
    bottom: 20,
    top: 80,
    containLabel: true
  },
  legend: {
    top: 50
  },
  series: [
    { name: '订单交付数量', type: 'line', smooth: true },
  ],
  toolbox: {
    feature: {
      // 数据区域缩放
      dataZoom: {
        yAxisIndex: false // Y轴不缩放
      },
      brush: {
        type: ['lineX', 'clear'] // 区域缩放按钮、还原按钮
      },
      saveAsImage: { show: true, name: '交易状况' } // 保存为图片
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    padding: [5, 10]
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisTick: {
      show: false
    }
  },
  yAxis: {
    axisTick: {
      show: false
    }
  }
}) as EChartsOption

/** 交付用时配置 */
const deliverTimeChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'item',
    confine: true,
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'right'
  },
  // roseType: 'area',
  series: [
    {
      name: '交付用时',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: '一周内' },
        { value: 735, name: '一月内' },
        { value: 580, name: '两月内' },
        { value: 484, name: '三月内' },
      ]
    }
  ]
}) as EChartsOption

/** 初始化 **/
onMounted(async () => {
  // await getTradeStatisticsSummary()
})
</script>
<style lang="scss" scoped>
.summary {
  .el-col {
    margin-bottom: 1rem;
  }
}
</style>
